<template>
  <el-form ref="ruleForm" :model="form" label-width="100px" style="margin: 0 auto;width:100%;">
    <el-form-item label="目录">
      <el-select v-model="form.xftId" class="filter-item" style="width: 100%" clearable disabled>
        <el-option v-for="item in ggTypes" :key="item.id" :label="item.typeName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="文件" prop="gysId">
      <el-upload
        class="upload-demo"
        :action="uploadpath"
        :headers="uoloadheaders"
        :on-success="handleAvatarSuccess"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :file-list="fileList"
        name="uploadfile_ant"
      >
        <el-button size="small" icon="el-icon-upload" type="primary">选择文件</el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="文件标签" prop="name">
      <el-input v-model="fileLabel" placeholder="文件标签，用';'隔开" />
    </el-form-item>
    <div style="text-align:center;">
      <el-button type="primary" :disabled="upVisible" @click="save('ruleForm')">提交</el-button>
      <el-button type="danger" @click="closePage">取消</el-button>
    </div>
  </el-form>
</template>

<script>

import { getAllLeafNode } from '@/api/catalogDetail'
import { saveData, checkUploadFile } from '@/api/projectFile'
import { getToken } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'
import { getId } from '@/api/user'

export default {
  inject: ['getList'],
  props: { // 第二种方式
    link: {
      type: String,
      required: true
    },
    xiangmu: {
      type: String,
      required: true
    },
    flag: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {},
      uploadpath: '',
      name: '',
      batchCode: '',
      fileLabel: '',
      uoloadheaders: {},
      dialogVisible: false,
      upVisible: true,
      visitPath: null,
      ggTypes: [],
      percent: 0, // 上传进度
      fileData: '', // 文件上传数据（多文件合一）
      fileList: [], // upload多文件数组
      singleFilePart: {
        file: '',
        fileList: [],
        partIndex: 0, // 当前分片
        partNum: 0, // 总分片数
        fileName: '', // 文件名
        fileUid: '' // 文件uuid
      },
      multipleFilePartMinio: {
        fileList: [],
        fileData: []
      },
      relativePath: null
    }
  },
  mounted() {
    this.getDetailed()
  },
  methods: {
    getDetailed() {
      getAllLeafNode({ xiangmuId: this.xiangmu }).then(response => {
        this.form.xftId = this.link
        this.ggTypes = response.data
      }).catch(function() {
      })

      this.batchCode = ''
      getId().then(response => {
        this.batchCode = response.data

        var path = '/projectFile/uploadFile?xftId=' + this.link + '&xiangmuId=' + this.xiangmu + '&batchCode=' + this.batchCode
        this.uploadpath = process.env.VUE_APP_BASE_API + path
        this.uoloadheaders = { 'X-Token': getToken() }
      })
    },
    handleAvatarSuccess(res, file) {
      const that = this
      this.uploadLoading = false
      if (res.code === 20000) {
        this.form = res.data
        this.upVisible = false
        Message({
          message: '上传成功',
          type: 'success',
          duration: 5 * 1000
        })
      } else {
        // this.upVisible = false
        // Message({
        //   message: res.msg,
        //   type: 'error',
        //   duration: 5 * 1000
        // })

        MessageBox.confirm(res.msg, '确定', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = process.env.VUE_APP_BASE_API + '/projectFile/newUploadFile'
          var fileParam = new FormData()

          fileParam.append('filePart', that.singleFilePart.file.raw)
          fileParam.append('xftId', that.link)
          fileParam.append('xiangmuId', that.xiangmu)
          fileParam.append('batchCode', that.batchCode)

          this.$upFile(url, fileParam, null, resp => {
            const res1 = resp.data
            if (res1.code === 20000) {
              this.form = res1.data
              this.upVisible = false
              Message({
                message: '上传成功',
                type: 'success',
                duration: 5 * 1000
              })
            }
          })
        })
      }
    },
    // 移除
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 选取文件超过数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 监控上传文件列表
    handleChange(file, fileList) {
      this.singleFilePart.file = file
      this.singleFilePart.fileList = []
      this.singleFilePart.fileList.push(file)
      this.singleFilePart.fileName = file.name

      const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        fileList.pop()
      }
      this.fileList = fileList
    },
    // 下面是单文件分片上传的一些方法
    selectSinglePartFile(file, fileList) {
      this.singleFilePart.file = file
      this.singleFilePart.fileList = []
      this.singleFilePart.fileList.push(file)
      this.singleFilePart.fileName = file.name
      console.log('单文件分片上传->选中的文件：', this.singleFilePart.file)
    },
    removeSingleFilePart(file, fileList) {
      this.singleFilePart.file = ''
      console.log('单文件分片上传->移除选中的文件：', this.singleFilePart.file)
    },
    singleFilePartUpload() {
      const that = this
      checkUploadFile({ xftId: this.link, originalName: this.singleFilePart.fileName }).then(response => {
        const loading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const partSize = 8 // MB
        this.singleFilePart.fileUid = that.singleFilePart.file.uid
        this.singleFilePart.partNum = Math.ceil(that.singleFilePart.file.size / 1024 / 1024 / partSize) // 2MB一片

        for (let i = 0; i < this.singleFilePart.partNum; i++) {
          const url = process.env.VUE_APP_BASE_API + '/projectFile/singleFilePartUpload'
          var fileParam = new FormData()
          fileParam.append('filePart', this.singleFilePart.file.raw.slice(i * 1024 * 1024 * partSize, (i + 1) * 1024 * 1024 * partSize))
          fileParam.append('partIndex', i)
          fileParam.append('partNum', this.singleFilePart.partNum)
          fileParam.append('fileName', this.singleFilePart.fileName)
          fileParam.append('fileUid', this.singleFilePart.fileUid)
          fileParam.append('fileSize', that.singleFilePart.file.size)

          this.$upFile(url, fileParam, null, resp => {
            const res = resp.data
            // 判断最后一个分片文件传完之后，后台检验文件上传情况
            if (res.code === 200) {
              if (i === parseInt(res.msg)) {
                var info1 = '当前分片 ' + i + ' 上传成功！' + ';返回的分片是 ' + res.msg
                console.log(info1)
              } else {
                var info2 = '当前分片 ' + i + ' 上传失败！' + ';返回的分片是 ' + res.msg
                console.log(info2)
              }

              if (res.msg2 !== null && res.msg2 !== '' && res.msg2 !== undefined) {
                loading.close()
                this.$message.success('单文件分片上传完成')
                this.relativePath = res.msg2
                this.upVisible = false
              }
            } else {
              loading.close()
              this.$message.error(res.msg)
            }
          })
        }
      }).catch(response => {
        MessageBox.confirm(response.message, '确定', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '上传中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const partSize = 8 // MB
          this.singleFilePart.fileUid = that.singleFilePart.file.uid
          this.singleFilePart.partNum = Math.ceil(that.singleFilePart.file.size / 1024 / 1024 / partSize) // 2MB一片

          for (let i = 0; i < this.singleFilePart.partNum; i++) {
            const url = process.env.VUE_APP_BASE_API + '/projectFile/singleFilePartUpload'
            var fileParam = new FormData()
            fileParam.append('filePart', this.singleFilePart.file.raw.slice(i * 1024 * 1024 * partSize, (i + 1) * 1024 * 1024 * partSize))
            fileParam.append('partIndex', i)
            fileParam.append('partNum', this.singleFilePart.partNum)
            fileParam.append('fileName', this.singleFilePart.fileName)
            fileParam.append('fileUid', this.singleFilePart.fileUid)
            fileParam.append('fileSize', that.singleFilePart.file.size)

            this.$upFile(url, fileParam, null, resp => {
              const res = resp.data
              // 判断最后一个分片文件传完之后，后台检验文件上传情况
              if (res.code === 200) {
                if (i === parseInt(res.msg)) {
                  var info1 = '当前分片 ' + i + ' 上传成功！' + ';返回的分片是 ' + res.msg
                  console.log(info1)
                } else {
                  var info2 = '当前分片 ' + i + ' 上传失败！' + ';返回的分片是 ' + res.msg
                  console.log(info2)
                }

                if (res.msg2 !== null && res.msg2 !== '' && res.msg2 !== undefined) {
                  loading.close()
                  this.$message.success('单文件分片上传完成')
                  this.relativePath = res.msg2
                  this.upVisible = false
                }
              } else {
                loading.close()
                this.$message.error(res.msg)
              }
            })
          }
        })
      })
    },
    // 确认添加问题
    async save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          this.form.xftId = this.link
          this.form.xiangmuId = this.xiangmu
          this.form.batchCode = this.batchCode
          this.form.originalName = this.singleFilePart.fileName
          this.form.relativePath = this.relativePath
          this.form.fileLabel = this.fileLabel
          this.form.fileSize = this.singleFilePart.file.size
          this.form.type = this.flag
          this.form.approvelState = '2'

          saveData(this.form).then(response => {
            Message({
              message: '新增成功',
              type: 'success',
              duration: 5 * 1000
            })
            this.$emit('update:visible', false)
            loading.close()
            this.getList()
          }).catch(response => {
            this.getList()
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    closePage() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>

</style>
